/**
 * axios的基本api
 * // 发送 POST 请求
 * axios({
 *  method: 'post',
 *  url: '/user/12345',
 *  data: {
 *    firstName: 'Fred',
 *    lastName: 'Flintstone'
 *  }
 *});
 *
 */

import axios from "axios";
import store from "@/store";
import router from "@/router";

// 创建axios实例
const request = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: "http://localhost/api",
  // 超时
  timeout: 10000,
  // 设置Content-Type，规定了前后端的交互使用json
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

request.interceptors.request.use(
  (config) => {
    let token = store.state.user.token;
    let userName = store.state.user.userName;
    if (token) {
      //'Bearer '
      config.headers["Authorization"] = token;
    }
    if (userName) {
      config.headers["userName"] = userName;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      store.dispatch("LOGOUT");
      router.push({ name: "login" });
      ElMessage.error("登录已过期，请重新登录");
    }
    return Promise.reject(error);
  }
);

export default request;
